package com.edgclub.edg.fragment;

import android.content.Intent;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.ChatActivity;
import com.edgclub.edg.activity.GroupDetailsActivity;
import com.edgclub.edg.activity.UserInfoOtherActivity;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.param.MessageParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.huanxin.db.InviteMessgeDao;
import com.edgclub.edg.model.GroupBean;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.GroupListData;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.adapter.EaseConversationAdapater;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.GroupChatBeanDao;
import com.hyphenate.easeui.dao.UserBeanDao;
import com.hyphenate.easeui.model.ChatBean;
import com.hyphenate.easeui.model.GroupChatBean;
import com.hyphenate.easeui.model.UserBean;
import com.hyphenate.easeui.model.UserChatListData;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

import java.util.HashMap;
import java.util.List;

public class ChatListFragment extends EaseConversationListFragment implements VolleyListener{

	private TextView errorText;
	List<EMConversation> conversationList;
	public static ChatListFragment newInstance(String text) {
		ChatListFragment f = new ChatListFragment();
		return f;
	}
	@Override
	protected void initView() {
		super.initView();
		setUserid(GuZhiApplication.getInstance().getUserId());
		View errorView = (LinearLayout) View.inflate(getActivity(), R.layout.em_chat_neterror_item, null);
		errorItemContainer.addView(errorView);
		errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).register(this);
	}

	@Override
	protected void setUpView() {
		super.setUpView();

		// 注册上下文菜单
		registerForContextMenu(conversationListView);

		hideTitleBar();
		hideQuery();
		conversationListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				EMConversation conversation = conversationListView.getItem(position);
				String username = conversation.conversationId();
				if (username.equals(EMClient.getInstance().getCurrentUser()))
					Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
				else {
					// 进入聊天页面
					Intent intent = new Intent(getActivity(), ChatActivity.class);
					ChatBean chatBean=new ChatBean();
					chatBean.setImid(conversation.conversationId());
					if(conversation.isGroup()){
						if(conversation.getType() == EMConversation.EMConversationType.GroupChat){
							// it's group chat
							chatBean.setChatType(Constant.CHATTYPE_GROUP);
							GroupChatBean userBean= (GroupChatBean) DaoHelper.getInstance(getActivity(), EaseConstant.DB_NAME_GROUP).getTypeId(GroupChatBeanDao.Properties.Ggimid,chatBean.getImid());
							if(null!=userBean) {
								chatBean.setName(userBean.getGname());
								chatBean.setGroupid(userBean.getGroupid());
								chatBean.setLogo(userBean.getLogo());
								chatBean.setGno(userBean.getGno());
							}
						}
					}else{
						UserBean userBean=	(UserBean) DaoHelper.getInstance(getActivity(), EaseConstant.DB_NAME_CHAT).getTypeId(UserBeanDao.Properties.Imid,conversation.conversationId());
						if(null!=userBean) {
							chatBean.setId(userBean.getId());
							chatBean.setName(userBean.getNick());
							chatBean.setGno(userBean.getGzno());
							chatBean.setUsername(userBean.getUsername());
							chatBean.setLogo(userBean.getLogo());
						}
						chatBean.setChatType(Constant.CHATTYPE_SINGLE);
					}
					intent.putExtra("chatBean",chatBean);
					startActivity(intent);
				}
			}
		});

		conversationListView.setUserIconClickListener(new EaseConversationAdapater.UserIconClickListener() {
			@Override
			public void onUserIconClick(UserBean userBean) {
				User user = new User();
				user.setId(userBean.getId());
				Intent intent = new Intent(getActivity(), UserInfoOtherActivity.class);
				intent.putExtra("user", user);
				getActivity().startActivity(intent);
			}

			@Override
			public void onGroupIconClick(GroupChatBean userBean) {

				if (null != userBean){
					Intent intent=new Intent(getActivity(), GroupDetailsActivity.class);
					intent.putExtra("groupid",userBean.getGroupid());
					intent.putExtra("groupname",userBean.getGname());
					startActivity(intent);
				}
			}
		});
		updateChat();
	}
	@Override
	protected void onConnectionDisconnected() {
		super.onConnectionDisconnected();
//		if (NetUtils.hasNetwork(getActivity())){
//			errorText.setText(R.string.can_not_connect_chat_server_connection);
//		} else {
//			errorText.setText(R.string.the_current_network);
//		}
	}


	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		boolean deleteMessage = false;
		/*if (item.getItemId() == R.id.delete_message) {
			deleteMessage = true;
		} else*/ if (item.getItemId() == R.id.delete_conversation) {
			deleteMessage = false;
		}
		EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
		if (tobeDeleteCons == null) {
			return true;
		}
		try {
			// 删除此会话
			EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), deleteMessage);
			InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
			inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		refresh();
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("event", BroadCastEvent.CHATLIST_NOMESS);
		int num=EMClient.getInstance().chatManager().getAllConversations().size();
		if(num>0)
			hashMap.put("obj", true);
		else
			hashMap.put("obj",false);
		hashMap.put("key",0);
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).post(hashMap);
		return true;
	}
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		refresh();
	}
	public void refresh_mian(String imid,int type){
		if(type==1){
			if(!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_CHAT).isHas(UserBeanDao.Properties.Imid,imid)){
				MessageParam messageParam = new MessageParam();
				messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
				messageParam.setImids(imid);
				new FriendApi(getActivity()).getUserFromIm(messageParam, this);
			}
		}else if(type==2){
			try {
				if(!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_GROUP).isHas(GroupChatBeanDao.Properties.Ggimid,imid)){
                    MessageParam messageParam = new MessageParam();
                    messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
                    messageParam.setGimid(imid);
                    new FriendApi(getActivity()).getGroupFromIm(messageParam, this);
                }
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		refresh();

	}
	@Subscribe
	public void refreshListView(HashMap<String, Object> map){
			String event = (String) map.get("event");
			if (null!=event&&BroadCastEvent.CHATLIST_REFRESH.equals(event)) {
				refresh();
			}
	}

	@Override
	public void onStart(String tag) {

	}

	@Override
	public void onSuccess(String response, String tag) {
		if (JSONHelper.isSuccess(response)) {
			if (tag.equals(ApiConfig.APIURL.URL_From_USER)) {
				UserChatListData data = JsonUtil.getMode(response,
						UserChatListData.class);
				if(null!=data&&null!=data.getData()) {
					for (UserBean user : data.getData()) {
						if(!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_CHAT).isHas(UserBeanDao.Properties.Imid,user.getImid()))
						DaoHelper.getInstance(getActivity(),Constant.DB_NAME_CHAT).insert(user);
					}

				}
			}else if(tag.equals(ApiConfig.APIURL.URL_From_GROUP)){
				GroupListData data = JsonUtil.getMode(response,
						GroupListData.class);
				if(null!=data&&null!=data.getData()) {
					for (GroupBean groupBean : data.getData()) {
						if(!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_GROUP).isHas(GroupChatBeanDao.Properties.Ggimid,groupBean.getGimid()))
							DaoHelper.getInstance(getActivity(),Constant.DB_NAME_GROUP).insert(groupBean);
						else
							DaoHelper.getInstance(getActivity(),Constant.DB_NAME_GROUP).update(groupBean);
					}
				}
			}
			refresh();
		}
	}

	@Override
	public void onFaile(VolleyError volleyError, String tag) {
		ResultCode.toastVolleyError(getActivity(), volleyError);
	}

	private void updateChat(){
		String loadkey="";
		String loadgroupkey="";
		List<EMConversation> conversationsList=loadConversationList();
		if(null!=conversationsList) {
			for (EMConversation conversation : conversationsList) {

			}
		}
		for(EMConversation message:conversationsList) {
			if(!message.isGroup()){

				if (!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_CHAT).isHas(UserBeanDao.Properties.Imid,message.conversationId())) {
					loadkey += message.conversationId() + ",";
				}
			}else {
				if (!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_GROUP).isHas(GroupChatBeanDao.Properties.Ggimid,message.conversationId())) {
					loadgroupkey += message.conversationId() + ",";
				}

			}
		}

		if(loadkey.length()!=0) {
			MessageParam messageParam = new MessageParam();
			messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
			messageParam.setImids(loadkey);
			new FriendApi(getActivity()).getUserFromIm(messageParam, this);
		}
		if(loadgroupkey.length()!=0) {
			MessageParam messageParam = new MessageParam();
			messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
			messageParam.setGimid(loadgroupkey);
			new FriendApi(getActivity()).getGroupFromIm(messageParam, this);
		}
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).unregister(this);
	}
}
